 package com.example.userclient.custom

import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.widget.Toast
import androidx.appcompat.widget.AppCompatImageView
import com.example.userclient.Main.ClientInfoHolder
import com.example.userclient.remote.AppExecutors
import java.lang.ref.SoftReference
import java.net.HttpURLConnection
import java.net.URL


 class  CustomCircleImageView : AppCompatImageView, CustomImageURL {
     //画笔
     private var mPaint: Paint? = null

     //圆形图片的半径
     private var mRadius = 0

     //图片的宿放比例
     private var mScale = 0f
    constructor(context: Context) : super(context)
    constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0)
    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(
            context,
            attributeSet,
            defStyleAttr
    )

    private val GET_DATA_SUCCESS = 1
    private val NETWORK_ERROR = 2
    private val SERVER_ERROR = 3
     override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
         super.onMeasure(widthMeasureSpec, heightMeasureSpec)
         val size = measuredWidth.coerceAtLeast(measuredHeight)
         mRadius = size / 2
         setMeasuredDimension(size, size)
     }

     override fun onDraw(canvas: Canvas?) {
         mPaint = Paint()

         val drawable = drawable



         if (null != drawable) {
             val bitmap =( drawable as BitmapDrawable).bitmap;
             val bitmapShader =  BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
             //计算缩放比例
             mScale = (mRadius * 2.0f) / Math.min(bitmap.getHeight(), bitmap.getWidth());

             var matrix =  Matrix();
             matrix.setScale(mScale, mScale);
             bitmapShader.setLocalMatrix(matrix);
             mPaint?.setShader(bitmapShader);
             //画圆形，指定好坐标，半径，画笔
             canvas?.drawCircle(mRadius.toFloat(), mRadius.toFloat(), mRadius.toFloat(), mPaint!!);
         } else {
             super.onDraw(canvas);
         }

     }

     private var callBackHandler = Handler(Looper.getMainLooper()){
        when(it.what){
            GET_DATA_SUCCESS -> {
                val bitmap = it.obj as Bitmap
                setImageBitmap(bitmap)
                Log.i("CustomImageView", "setBitMap")
                return@Handler true
            }
            NETWORK_ERROR -> {
                Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                Log.i("CustomImageView", "NETWORK_ERROR")
                return@Handler true
            }
            SERVER_ERROR -> {
                Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                Log.i("CustomImageView", "SERVER_ERROR")
                return@Handler true
            }
            else -> {
                Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                Log.i("CustomImageView", "else")
                return@Handler true
            }
        }

    }


    override fun setImageURL(path: String?) {
        Log.i("CustomImageView", "path：$path")
        //开启一个线程用于联网
        if (!path.isNullOrEmpty()){
            Log.i("CustomImageView", "size:${ClientInfoHolder.map.size}")
            if( ClientInfoHolder.map[path]?.get()!=null){
                val bitmap = ClientInfoHolder.map[path]?.get()
                //利用Message把图片发给Handler
                val msg = Message.obtain()
                msg.obj = bitmap
                msg.what = GET_DATA_SUCCESS;
                callBackHandler.sendMessage(msg)
                Log.i("CustomImageView", "cached 1!")
                return
            }
            AppExecutors.startTask(Thread {
                try {
                    val url = URL(path)
                    val connection = url.openConnection() as HttpURLConnection
                    //使用GET方法访问网络
                    connection.requestMethod = "GET"
                    //超时时间为10
                    connection.connectTimeout = 10000
                    //获取返回码
                    var code = connection.responseCode
                    val inputStream = connection.inputStream
                    if (code == 200) {
                        //使用工厂把网络的输入流生产Bitmap
                        val bitmap = BitmapFactory.decodeStream(inputStream)
                        //利用Message把图片发给Handler
                        val msg = Message.obtain()

                        val value = SoftReference(bitmap)
                        ClientInfoHolder.map[path] = value
                        Log.i("CustomImageView", "Mod:size:${ClientInfoHolder.map.size}")
                        msg.obj = bitmap
                        msg.what = GET_DATA_SUCCESS;
                        callBackHandler.sendMessage(msg)
                        Log.i("CustomImageView", "apply from network")
                    } else {
                        //服务启发生错误
                        callBackHandler.sendEmptyMessage(SERVER_ERROR)
                        Log.i("CustomImageView", "apply error")
                    }
                    inputStream.close()
                } catch (e: Exception) {
                    e.printStackTrace()

                }
            })
            Log.i("CustomImageView", "finish")
        }
    }


}